<template>
  <div class="updateModal">
    <a-modal
      :visible="addProductModal"
      title="添加商品"
      @cancel="cancel"
      @ok="maodalAddProduct"
      :destroyOnClose="destory"
      width="1000px"
    >
      <a-form-model
        id="components-form-demo-normal-login"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        ref="ruleForm"
        :model="newProduct"
        :rules="rules"
        class="login-form"
      >
        <a-form-model-item label="商品名称" prop="name">
          <a-input v-model="newProduct.name" placeholder="请输入商品名称">
            <a-icon slot="prefix" type="user" style="color: rgba(0,0,0,.25)" />
          </a-input>
        </a-form-model-item>
        <a-form-model-item label="商品描述" prop="desc">
          <a-input v-model="newProduct.desc" placeholder="请输入商品描述" type="textarea">
            <a-icon slot="prefix" type="user" style="color: rgba(0,0,0,.25)" />
          </a-input>
        </a-form-model-item>
        <a-form-model-item label="商品价格" prop="price">
          <a-input
            prefix="￥"
            suffix="RMB"
            v-model="newProduct.price"
            placeholder="请输入商品价格"
            type="number"
          >
            <a-icon slot="prefix" type="user" style="color: rgba(0,0,0,.25)" />
          </a-input>
        </a-form-model-item>
        <a-form-model-item label="商品分类" prop="productCategory">
          <a-cascader
            v-model="newProduct.productCategory"
            :options="saveCategoryList"
            placeholder="请选择商品分类"
            change-on-select
            @change="onChange"
            :field-names="{ label: 'name', value: '_id', children: 'children' }"
          />
        </a-form-model-item>
        <a-form-model-item label="商品图片">
          <div class="clearfix">
            <!-- 注意：这里有坑，在这里卡了好久，一定要弄清楚路径，/api/img/upload只是后端上传图片的路径接口，但是这里前端devserve中配置代理的是/api，所以最终的路径是/api/api/img/upload -->
            <a-upload
              action="/api/api/img/upload"
              accept="image/*"
              name="image"
              list-type="picture-card"
              :headers="headers"
              :file-list="fileList"
              @preview="handlePreview"
              @change="handleChange"
            >
              <div v-if="fileList.length < 5">
                <a-icon type="plus" />
                <div class="ant-upload-text">上传</div>
              </div>
            </a-upload>
            <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
              <img alt="example" style="width: 100%" :src="previewImage" />
            </a-modal>
          </div>
        </a-form-model-item>
        <a-form-model-item label="商品详情">
          <!-- <Editor
            :init="{
              height: 300,
              menubar: 'favs file edit view insert format tools table help',
              menu: {
                file: { title: 'File', items: 'newdocument restoredraft | preview | print ' },
                edit: { title: 'Edit', items: 'undo redo | cut copy paste | selectall | searchreplace' },
                view: { title: 'View', items: 'code | visualaid visualchars visualblocks | spellchecker | preview fullscreen' },
                insert: { title: 'Insert', items: 'image link media template codesample inserttable | charmap emoticons hr | pagebreak nonbreaking anchor toc | insertdatetime' },
                format: { title: 'Format', items: 'bold italic underline strikethrough superscript subscript codeformat | formats blockformats fontformats fontsizes align lineheight | forecolor backcolor | removeformat' },
                tools: { title: 'Tools', items: 'spellchecker spellcheckerlanguage | code wordcount' },
                table: { title: 'Table', items: 'inserttable | cell row column | tableprops deletetable' },
                help: { title: 'Help', items: 'help' }
              },
              content_css: 'css/content.css',
              plugins: [
                'advlist autolink lists link image charmap print preview anchor',
                'searchreplace visualblocks code fullscreen',
                'insertdatetime media table paste code help wordcount'
              ],
              toolbar:
                'undo redo | formatselect | bold italic backcolor | \
                alignleft aligncenter alignright alignjustify | \
                bullist numlist outdent indent | removeformat | help'
            }"
          />-->
          <WangEditor @getWangrditorData="getWangrditorData" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import { addProduct, deleteImg } from '@/network/product.js'
import {
  getALLCategory
} from '@/network/categorys.js'

//import Editor from '@tinymce/tinymce-vue';

import WangEditor from './WangEditor'
function getBase64 (file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
export default {
  name: 'addNewProduct',
  data () {
    return {
      addProductModal: false,
      labelCol: {
        span: 6
      },
      wrapperCol: {
        span: 15
      },
      newProduct: {
        name: '',
        desc: '',
        price: '',
        categoryId: '',
        pCategoryId: '',
        detail: '',
        imgs: [],
        productCategory: []
      },
      rules: {
        name: [
          { required: true, message: '请输入商品名称!', trigger: 'blur' },
        ],
        desc: [
          { required: true, message: '请输入商品描述!', trigger: 'blur' },
        ],
        price: [
          { required: true, message: '请输入商品价格!', trigger: 'blur' },
        ],
        productCategory: [
          { required: true, message: '请选择商品分类!', trigger: 'blur' },
        ]
      },
      saveCategoryList: [],   //用于保存所有分类
      destory: true,
      previewVisible: false,  //预览图片的显示与否
      previewImage: '',
      fileList: [

      ],
      headers: {
        authorization: window.localStorage.getItem('NiuToken')
      }
    };
  },
  components: {
    //Editor,
    WangEditor
  },
  computed: {

  },
  mounted () {
    this.getALLCategory(0)
  },
  methods: {
    //获取所有分类
    getALLCategory (parentIdz) {
      getALLCategory(parentIdz).then(res => {
        console.log(res)
        if (res.data.status === 200) {
          //得到一级分类后，递归遍历查看是否有二级分类或者三级分类，如果有，添加到对应父分类的children中
          if (res.data.data.length != 0) {  //当该级分类数组为空的时候，当前递归结束
            //不为空继续
            for (let item of res.data.data) {
              //第一次遍历，构造一个符合属性结构的数据
              const treeCategory = {
                parentId: item.parentId,
                _id: item._id,
                key: parentIdz + item._id,
                name: item.name,
                children: []
              }
              this.saveCategoryList.push(treeCategory)
            }
          }
          console.log(this.saveCategoryList)
          for (let item2 of this.saveCategoryList) {
            getALLCategory(item2._id).then(res => {
              if (res.data.data.length != 0) {
                for (let item3 of res.data.data) {
                  const treeCategory = {
                    parentId: item3.parentId,
                    _id: item3._id,
                    key: item2.key + item3._id,
                    name: item3.name,
                    children: []
                  }
                  item2.children.push(treeCategory)
                }
              }
            })
          }
          console.log(this.saveCategoryList)
        }
      })
    },
    onChange (value) {
      console.log(value)
      if (value.length == 1) {
        this.newProduct.pCategoryId = '0'
        this.newProduct.categoryId = value[0]
      } else if (value.length == 2) {
        this.newProduct.pCategoryId = value[0]
        this.newProduct.categoryId = value[1]
      }
    },
    //添加商品的取消按钮
    cancel () {
      this.addProductModal = false
    },
    //打开添加商品的modal
    show () {
      this.addProductModal = true
    },
    //modal的确认按钮
    maodalAddProduct () {
      const params = {
        name: this.newProduct.name,
        desc: this.newProduct.desc,
        price: this.newProduct.price,
        categoryId: this.newProduct.categoryId,
        pCategoryId: this.newProduct.pCategoryId,
        detail: this.newProduct.detail,
        imgs: this.newProduct.imgs
      }
      addProduct(params).then(res => {
        console.log(res)
        if (res.data.status === 200) {
          this.$message.success('添加商品成功')
          this.addProductModal = false
          this.$emit('refreshTable')
        }
      })
    },
    //富文本编辑器的内容
    getWangrditorData (WangrditorData) {
      this.newProduct.detail = WangrditorData
    },
    //关闭图片预览
    handleCancel () {
      this.previewVisible = false;
    },
    //点击文件链接或预览图标时的回调
    async handlePreview (file) {
      console.log(file)
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    //上传文件改变时的状态
    async handleChange ({ file, fileList }) {
      console.log(file, fileList)
      if (file.status === 'done') {
        const result = file.response
        if (result.status === 200) {
          this.$message.success('图片上传成功')
          const { name, url } = result.data
          file = fileList[fileList.length - 1]
          file.name = name
          file.url = url
          this.newProduct.imgs.push(url)
        } else {
          this.$message.error('图片上传失败')
        }
      } else if (file.status === 'removed') {
        const result = await deleteImg({ name: file.name })
        if (result.status === 200) {
          this.$message.success('删除图片成功')
        } else {
          this.$message.error('删除图片失败')
        }
      }
      this.fileList = fileList
    }
  },

};
</script>

<style scoped>
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
